import 'package:dio/dio.dart';
import '../public.dart';
import 'navigate_service.dart';
import 'variable.dart';
import 'dart:math';

class Application {
  static GetIt getIt = GetIt.instance;

  /// 项目初始化
  static Future init() async {
    /// 注册服务
    getIt.registerSingleton(NavigateService());
    await StorageManager.init();
    await initHttp();
  }

  static NavigateService get navigateService => getIt<NavigateService>();

  static Future initHttp() async {
    BaseOptions options = HttpUtil.getDefOptions();
    // 设置正确的baseUrl
    options.baseUrl = VariableConfig().api;
    // 允许所有状态码通过验证
    options.validateStatus = (status) => true;
    // 设置超时时间
    options.connectTimeout = Duration(seconds: 30);
    options.receiveTimeout = Duration(seconds: 30);

    // 拦截配置
    HttpConfig config = HttpConfig(
      options: options,
      interceptorsWrapper: InterceptorsWrapper(
        onRequest:
            (RequestOptions options, RequestInterceptorHandler handler) async {
              // 强制设置正确的baseUrl
              options.baseUrl = VariableConfig().api;
              // 修复URL路径格式问题，避免重复斜杠
              if (options.baseUrl.endsWith('/') &&
                  options.path.startsWith('/')) {
                options.path = options.path.substring(1);
              }
              // 获取token
              final token = StorageManager.ls.getItem("token");
              // 添加必要的请求头
              options.headers["x-gift-token"] = token;
              options.headers["x-gift-timestamp"] = DateTime.now()
                  .millisecondsSinceEpoch
                  .toString();
              final random = Random();
              final randomNumber = random.nextInt(900000) + 100000;
              options.headers["x-gift-num"] = randomNumber.toString();
              options.headers['Accept'] = 'application/json, text/plain, */*';
              options.headers['Content-Type'] = 'application/json';
              // 只对非GET请求且非FormData的数据进行加密
              if (options.method.toUpperCase() != 'GET' &&
                  options.data != null &&
                  options.data is! FormData) {
                try {
                  final encryptedData = CryptoUtil.encryptData(options.data);
                  options.data = {'data': encryptedData};
                  handler.next(options);
                } catch (e) {
                  // 加密失败时，直接传递原始数据
                  handler.next(options);
                }
              } else {
                handler.next(options);
              }
            },
      ),
    );
    // 设置
    HttpUtil().setConfig(config);
  }
}
